#include "StdAfx.h"

FileBuffer::FileBuffer(CMpqFile& file)
{
	ui32 size = file.GetSize();
	m_data.resize(size);
	file.Read(0, size, &m_data.front());
}

FileBuffer::~FileBuffer()
{
	m_data.clear();
}

void FileBuffer::Write(ui32 pos, ui32 size, void* pData)
{
	if(pos + size >= m_data.size())
		return;
	memcpy(&m_data[pos], pData, size);
}

void FileBuffer::Read(ui32 pos, ui32 size, void* pData)
{
	if(pos + size >= m_data.size())
		return;
	memcpy(pData, &m_data.front() + pos, size);
}

void FileBuffer::Append(ui32 pos, ui32 size, void* pData)
{
	ui8* start = (ui8*)pData;

	m_data.insert(m_data.begin() + pos, start, start + size);
}

void FileBuffer::Erase(ui32 pos, ui32 size)
{
	std::vector<ui8> tmp;
	tmp.resize(m_data.size() - size);
	if(pos > 0)
		std::copy(&m_data[0], &m_data[pos], tmp.begin());
	if(size > 0)
		std::copy(&m_data[pos + size], &m_data[m_data.size() - 1], &tmp[pos]);
	m_data = tmp;
}

void FileBuffer::SaveToFile(std::string szFileName)
{
	FILE* f = fopen(szFileName.c_str(), "wb");
	if(!f)
		return;
	fwrite(&m_data.front(), m_data.size(), 1, f);
	fclose(f);
}